package org.example.commonapi.response.pictureDocument;

import com.google.gson.Gson;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.example.commonapi.util.oss.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@Data
@Slf4j
public class PictureDocumentListener extends WebSocketListener {

    private OssService ossService;

    private Gson gson = new Gson();
    String downloadLink = null;
    String type;
    public PictureDocumentListener(String type, OssService ossService)  {
        this.type = type;
        this.ossService = ossService;
    }
    /**
     * websocket连接关闭标志
     */
    private Boolean wsCloseFlag = false;
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        PictureDocumentResponse pictureDocumentResponse = gson.fromJson(text, PictureDocumentResponse.class);
        if (pictureDocumentResponse.getHeader().getCode() != 0) {
            System.out.println("发生错误，错误码为：" + pictureDocumentResponse.getHeader().getCode());
            System.out.println("本次请求的sid为：" + pictureDocumentResponse.getHeader().getSid());
        }
        if (pictureDocumentResponse.getHeader().getStatus() == 1) {
            try {
                System.out.println("目标文件");
                System.out.println(type);
                String suffix = null;
                if ( type.equals("0") ) {
                    suffix = "xlsx";
                }
                if ( type.equals("1") ) {
                    suffix = "doc";
                }
                if ( type.equals("2") ) {
                    suffix = "pptx";
                }
                String OUTPUT_FILE_PATH = "D:\\Project\\Java\\iflytek-education\\common-api\\src\\main\\java\\org\\example\\commonapi\\response\\pictureDocument\\output\\result." + suffix;
                OutputStream outputStream = new FileOutputStream(OUTPUT_FILE_PATH);
                byte[] textBase64Decode = Base64.getDecoder().decode(pictureDocumentResponse.getPayload().getResult().getText());
                outputStream.write(textBase64Decode);
                outputStream.close();
                System.out.println("表格识别成功，文件保存路径为==>" + OUTPUT_FILE_PATH);
                File file = new File(OUTPUT_FILE_PATH);
                System.out.println(file);
                FileInputStream fileInputStream = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                downloadLink = ossService.upload(multipartFile);
                System.out.println("下载链接=》" + downloadLink);
                // 上传完毕 删除生成的文件
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("本次请求的sid==>" + pictureDocumentResponse.getHeader().getSid());
        } else if (pictureDocumentResponse.getHeader().getStatus() == 2) {
            // 可以关闭连接，释放资源
            webSocket.close(1000,"");
            wsCloseFlag = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        if (response != null) {
            int code = response.code();
            try {
                log.info("[Spark-chat-websocket]failure code:{} , boyd{}", code, response.body().string());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private FileItem getMultipartFile(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        int len = 8192;
        byte[] buffer = new byte[len];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
